import { Dialog } from 'vant'
import store from '../store'
import router from '../router'

var url = 'ws://localhost:8080/Ediandian/chat'
var ws;
var tt;
var lockReconnect = false;//避免重复连接
var Message = { 
  thumb_me: 0,
  payAttention_me:0
}

let websocket = {
  Init: function() {
    var result = JSON.parse(window.localStorage.getItem("result"))
    var token = result.token
    if ("WebSocket" in window) {
      ws = new WebSocket(url + '?token=' + token);
    } else if ("MozWebSocket" in window) {
      ws = new MozWebSocket(url + '?token=' + token);
    } else {
      console.log("您的浏览器不支持 WebSocket!");
      return;
    }

    ws.onmessage = function (e) {  
      onmessage(e)
    } 

    ws.onclose = onclose()

    ws.onopen = onopen()

    ws.onerror = onerror()
  },


  Send:function(type,fromName,toName,msg){
    let data = {
      type,
      fromName,
      toName,
      msg
    }
    let sendMsg= JSON.stringify(data)
    console.log("发送消息："+sendMsg)
    ws.send(sendMsg)
  },


  getWebSocket(){
    return ws;
  },


  getStatus() {
    if (ws.readyState == 0) {
      return "未连接";
    } else if (ws.readyState == 1) {
      return "已连接";
    } else if (ws.readyState == 2) {
      return "连接正在关闭";
    } else if (ws.readyState == 3) {
      return "连接已关闭";
    }
  },


  forceClose() { 
    clearTimeout(tt)
    console.log("强制关闭")
    ws.close()
  }
}

export default websocket

/**
 * 连接打开时
 */
function onopen() { 
  console.log("连接开启...")
  
  heartCheck.start();
}

/**
 * 接收消息时
 * @param {*} e 
 * @returns 
 */
function onmessage(e) {
    console.log("接收消息:" + e.data)
    let data = JSON.parse(e.data)
    console.log("消息data = "+data)
    //如果状态是0，强制下线
    console.log("接收消息状态:" + data.state)
    if(data.state == 0){ 
      window.localStorage.removeItem("result")
      websocket.forceClose();
      Dialog({
          message:data.msg
      }).then(() => { 
          router.push("/login")
          return ;
      })
      
    } else { 
      
      heartCheck.start()
      //这里对不同消息类型做相应处理
      if(data.type=='HeartBeat'){//心跳消息不做处理
        return
      }

      else if(data.type == '点赞'){ 
          let msg = data.msg
          let val = parseInt(msg)
          Message.thumb_me = val
          console.log("接收点赞信息处理后 Message = ",Message) 
      }

      else if(data.type == '关注'){ 
          let msg = data.msg
          let val = parseInt(msg)
          Message.payAttention_me = val
          console.log("接收关注消息处理后 Message = ",Message)
      }
      
      window.localStorage.setItem("Message",JSON.stringify(Message)) 
      store.commit("message/setMessage",Message)

    }
}



/**
 * 发生错误时
 */
function onerror(){ 
  console.log("连接发生错误...")
  reconnect()
}


/**
 * 连接关闭
 */
function onclose() { 
  console.log("连接关闭")
  reconnect()
}



function reconnect() {
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  tt && clearTimeout(tt);
  tt = setTimeout(function () {
    console.log("执行断线重连...");
    websocket.Init();
    lockReconnect = false;
  }, 4000);
}


//心跳检测
var heartCheck = {
  timeout: 1000 * 60 * 3,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function () {
    console.log("开始心跳检测");
    var self = this;
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout(function () {
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      console.log("心跳检测...");
      // ws.send("HeartBeat:");
      websocket.Send("HeartBeat","","","")
      self.serverTimeoutObj = setTimeout(function () {
        if (ws.readyState != 1) {
          ws.close();
        }
        // createWebSocket();
      }, self.timeout);
    }, this.timeout);
  },
}




